<template>
  <div class="chat-container">
    <div class="chat-intro">
      这是一个聚慧公司针对品牌产品的相关问题解答的AI助手，能够理解和回答您的问题，提供智能对话服务。
    </div>
    <div class="chat-messages" ref="messageContainer">
      <div v-for="(message, index) in messages" :key="index" :class="['message-wrapper', message.type]">
        <div class="avatar">
          <img :src="message.type === 'user' ? '/user-avatar.png' : '/bot-avatar.png'" :alt="message.type === 'user' ? '用户' : 'robot'">
        </div>
        <div class="message">
          <div class="message-content">{{ message.content }}</div>
        </div>
      </div>
    </div>
    <div class="chat-input">
      <input
        v-model="userInput"
        @keyup.enter="sendMessage"
        placeholder="请输入消息..."
        type="text"
      />
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import { createChatCompletion } from './api/coze'

// 存储聊天消息历史
const messages = ref([])
// 用户输入内容
const userInput = ref('')
// 消息容器的引用，用于滚动控制
const messageContainer = ref(null)
// 存储当前机器人正在生成的消息
const currentBotMessage = ref('')
// 用于存储SSE连接实例
const eventSource = ref(null)
// 用于跟踪已处理的内容
const processedContent = ref(new Set())

// 自动滚动到底部的函数
const scrollToBottom = async () => {
  await nextTick()
  if (messageContainer.value) {
    messageContainer.value.scrollTop = messageContainer.value.scrollHeight
  }
}

// 发送消息并处理响应
const sendMessage = async () => {
  // 检查输入是否为空
  if (!userInput.value.trim()) return
  
  // 添加用户消息到消息列表
  messages.value.push({
    type: 'user',
    content: userInput.value
  })

  const userMessage = userInput.value
  // 清空输入框
  userInput.value = ''

  try {
    // 创建一个空的机器人消息
    messages.value.push({
      type: 'bot',
      content: ''
    })

    // 调用API获取流式响应
    const response = await createChatCompletion(userMessage)
    // 将响应数据按行分割
    const lines = response.data.split('\n')

    // 添加延时函数
    const delay = ms => new Promise(resolve => setTimeout(resolve, ms))

    // 处理每一行数据
    for (const line of lines) {
      if (!line.trim() || !line.startsWith('data:')) continue

      const jsonStr = line.slice(5).trim()
      if (jsonStr === '[DONE]') break

      try {
        // 解析JSON数据
        const data = JSON.parse(jsonStr)
        // 处理来自assistant的answer类型消息
        if (data.role === 'assistant' && data.type === 'answer') {
          const lastMessage = messages.value[messages.value.length - 1]
          // 使用Set来跟踪已处理的内容，避免重复
          if (data.content && !processedContent.value.has(data.content)) {
            processedContent.value.add(data.content)
            lastMessage.content += data.content
            await scrollToBottom()
            await delay(100)
          }
          if (data.reasoning_content && !processedContent.value.has(data.reasoning_content)) {
            processedContent.value.add(data.reasoning_content)
            lastMessage.content += data.reasoning_content
            await scrollToBottom()
            await delay(100)
          }
        }
      } catch (parseError) {
        console.error('解析响应数据时出错:', parseError)
        messages.value[messages.value.length - 1].content = '消息解析失败，请重试。错误详情：' + parseError.message
      }
    }
  } catch (error) {
    console.error('API请求错误:', error)
    // 根据错误类型提供更具体的错误信息
    let errorMessage = '抱歉，发生了一些错误。'
    if (error.response) {
      // 服务器返回了错误状态码
      errorMessage += `服务器返回${error.response.status}错误：${error.response.data?.message || '未知错误'}`
    } else if (error.request) {
      // 请求已发出但没有收到响应
      errorMessage += '无法连接到服务器，请检查网络连接。'
    } else {
      // 请求配置出错
      errorMessage += `请求配置错误：${error.message}`
    }
    messages.value.push({
      type: 'bot',
      content: errorMessage
    })
  }
}
</script>

<style scoped>
.chat-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 24px;

.chat-intro {
  text-align: center;
  padding: 16px;
  margin-bottom: 20px;
  background-color: #2D2D2D;
  border-radius: 12px;
  color: #FFFFFF;
  font-size: 15px;
  line-height: 1.5;
}

  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #1E1E1E;
  color: #FFFFFF;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  margin-bottom: 24px;
  scrollbar-width: thin;
  scrollbar-color: #4A4A4A #1E1E1E;
}

.chat-messages::-webkit-scrollbar {
  width: 8px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #1E1E1E;
}

.chat-messages::-webkit-scrollbar-thumb {
  background-color: #4A4A4A;
  border-radius: 4px;
}

.message-wrapper {
  display: flex;
  align-items: flex-start;
  margin: 16px 0;
  gap: 12px;
}

.message-wrapper.user {
  flex-direction: row-reverse;
}

.avatar {
  width: 40px;
  height: 40px;
  flex-shrink: 0;
  border-radius: 50%;
  overflow: hidden;
  background-color: #2D2D2D;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.message {
  padding: 12px 16px;
  border-radius: 12px;
  max-width: calc(85% - 52px);
  line-height: 1.5;
  font-size: 15px;
  transition: all 0.3s ease;
}

.message-content {
  word-break: break-word;
  white-space: pre-wrap;
}

.user .message {
  background-color: #2B7FE0;
  color: white;
  border-bottom-right-radius: 4px;
}

.bot .message {
  background-color: #2D2D2D;
  color: #FFFFFF;
  border-bottom-left-radius: 4px;
}

.chat-input {
  display: flex;
  gap: 12px;
  background-color: #2D2D2D;
  padding: 16px;
  border-radius: 12px;
}

input {
  flex: 1;
  padding: 12px 16px;
  background-color: #1E1E1E;
  border: 1px solid #3E3E3E;
  border-radius: 8px;
  font-size: 15px;
  color: #FFFFFF;
  transition: border-color 0.3s ease;
}

input:focus {
  outline: none;
  border-color: #2B7FE0;
}

input::placeholder {
  color: #808080;
}

button {
  padding: 12px 24px;
  background-color: #2B7FE0;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 15px;
  font-weight: 500;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #1E6AC8;
}

@media (max-width: 768px) {
  .chat-container {
    padding: 16px;
  }

  .message {
    max-width: calc(90% - 52px);
  }

  .chat-input {
    padding: 12px;
  }

  button {
    padding: 12px 20px;
  }
}
</style>